from decimal import Decimal
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import SKU
from orders.serializer import OrderSettlementSerializer, OrderSerializer


class OrderSettlementView(APIView):
    """订单结算"""
    permission_classes = [IsAuthenticated]

    def get(self,request):
        """登录用户结算商品数据获取"""
        # 从redis用户购物车数据中获取勾选被勾选的商品sku_id和对应的数量count
        redis_conn = get_redis_connection('cart')

        # 从redis中set获取被勾选的商品sku_id

        user = request.user
        cart_selected_key = 'cart_selected_%s' % user.id

        sku_ids = redis_conn.smembers(cart_selected_key)

        # 从redis中hash中获取用户购物车所有的商品sku_id 和 对应的数量count

        cart_key = 'cart_%s' % user.id

        cart_dict = redis_conn.hgetall(cart_key)

        # 组织数据
        cart = {}

        for sku_id, count in cart_dict.items():
            cart[int(sku_id)] = int(count)

        # 2.根据商品id 获取商品对应的商品信息，组织运费

        skus = SKU.objects.filter(id__in=sku_ids)

        for sku in skus:
            # 给sku对象增加属性count,保存用户所需要结算的该商品数量count
            sku.count = cart[sku.id]

        # 组织运费
        freight = Decimal(10)

        # 3.序列化返回数据

        res_dict = {
            'freight':freight,
            'skus':skus
        }
        serializer = OrderSettlementSerializer(res_dict)

        return Response(serializer.data)


# POST /orders/
class OrdersView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderSerializer